import React, { useState } from 'react';
import styles from './style.less';

export interface Item {
  color: string;
  label?: string;
  value?: any;
}

interface ColorSelectorProps {
  data: Item[];
  onChange?: Function;
}

const ColorSelector: React.FC<ColorSelectorProps> = ({ data = [], onChange }) => {
  const [index, setIndex] = useState(-1);

  const getItemClassName = (itemIndex: number) => {
    return itemIndex === index ? (styles.color + ' ' + styles.select) : styles.color;
  };

  const handleClick = (value: any, itemIndex: number) => {
    setIndex(itemIndex);
    if (onChange instanceof Function) {
      onChange(value, itemIndex);
    }
  };

  return (
    <ul className={styles['color-selector']}>
      {data.map((item: Item, itemIndex: number) => {
        const { color, label, value } = item;
        return (
          <li className={styles['color-item']} onClick={() => handleClick(value, itemIndex)} key={color}>
            <div
              className={getItemClassName(itemIndex)}
              style={color ? { backgroundColor: color } : {}}
            />
            {label ? <span>{label}</span> : null}
          </li>
        );
      })}
    </ul>
  );
};

export default ColorSelector;
